﻿using Gasgoo.ShareLibrary.Framework.iDataProvider;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Orleans;
using Orleans.Hosting;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Storage;

namespace Gasgoo.ShareExtensions
{
    public static class GasgooStorageBuilderExtensions
    {
        /// <summary>
        /// 指定默认存储方式
        /// </summary>
        public static ISiloHostBuilder UseGasgooStorageAsDefault<T>(this ISiloHostBuilder builder, T factory) where T : IStorageFactory
        {
            return builder.UseGasgooStorage(ProviderConstants.DEFAULT_STORAGE_PROVIDER_NAME, factory);
        }

        /// <summary>
        /// 给指定Title指定
        /// </summary>
        /// <returns></returns>
        public static ISiloHostBuilder UseGasgooStorage<T>(this ISiloHostBuilder builder, string name, T factory) where T : IStorageFactory
        {
            return builder.ConfigureServices(services => services.UseGasgooStorage(name, factory));
        }

        /// <summary>
        /// 给指定Title指定
        /// </summary>
        /// <returns></returns>
        internal static IServiceCollection UseGasgooStorage<T>(this IServiceCollection services, string name, T factory) where T : IStorageFactory
        {
            services.TryAddSingleton(sp => sp.GetServiceByName<IGrainStorage>(ProviderConstants.DEFAULT_STORAGE_PROVIDER_NAME));
            services.AddSingletonNamedService(name, factory.Create);
            services.AddSingletonNamedService(name, (s, n) => (ILifecycleParticipant<ISiloLifecycle>)s.GetRequiredServiceByName<IGrainStorage>(n));
            return services;
        }
    }
}
